<!-- 只读代码编辑器组件 -->
<script setup lang="ts">
import * as monaco from "monaco-editor";
import {
  onMounted,
  ref,
  toRaw,
  withDefaults,
  defineProps,
  watch,
  toRef,
} from 'vue';

const codeEditorRef = ref();
const codeEditor = ref();

interface Props {
  value: string;      // 展示的代码内容
  language: string;   // 代码语言类型，例如 "java","javascript"、"python"
}

const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  language: "java",
});

// 监听语言变化，更新语法高亮
watch(() => props.language, (newLang) => {
  if (codeEditor.value) {
    const model = toRaw(codeEditor.value).getModel();
    if (model) {
      monaco.editor.setModelLanguage(model, newLang);
    }
  }
});

// 监听 value 变化，刷新展示的代码
watch(toRef(props, 'value'), (newVal) => {
  if (codeEditor.value) {
    const currentValue = toRaw(codeEditor.value).getValue();
    if (currentValue !== newVal) {
      toRaw(codeEditor.value).setValue(newVal);
    }
  }
});

onMounted(() => {
  if (!codeEditorRef.value) return;

  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    readOnly: true, // 👈 设置为只读模式
    automaticLayout: true,
    colorDecorators: true,
    folding: true,
    formatOnPaste: false,
    matchBrackets: "always",
    minimap: {
      enabled: false,
    },
    theme: "vs-dark",
    contextmenu: false, // 可选：禁用右键菜单
  });
});
</script>

<template>
  <div
    id="code-editor"
    ref="codeEditorRef"
    style="min-height: 400px; height: 75vh;"
  />
</template>

<style scoped></style>
